from fastapi import FastAPI
from tortoise import Tortoise, run_async
from tortoise.contrib.fastapi import register_tortoise

from app.config import get_settings
from app.logger import log

settings = get_settings()


MODELS = [
    "app.models.users",
    "app.models.doctors",
    "app.models.schedule",
    "app.models.studies",
    "app.models.plans",
]


def init_db(app: FastAPI) -> None:
    register_tortoise(
        app,
        db_url=str(settings.database_url),
        modules={"models": MODELS},
        generate_schemas=False,
        add_exception_handlers=True,
    )


async def generate_schema() -> None:
    log.info("Initializing Tortoise...")

    await Tortoise.init(
        db_url=str(settings.database_url),
        modules={"models": MODELS},
    )
    log.info("Generating database schema via Tortoise...")
    await Tortoise.generate_schemas()
    await Tortoise.close_connections()


if __name__ == "__main__":
    run_async(generate_schema())
